package com.tianqu.tms.www.transfer.action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.TransferAcceptedInfo;
import com.tianqu.tms.entity.TransferProcessHistory;
import com.tianqu.tms.www.transfer.actionform.TransferRgActionForm;
import com.tianqu.tms.www.transfer.viewhelper.TransferRgInputViewHelper;

/**
 * @author zhangxueliang 对图片进行上传和确认操作
 */
public class TransferCarImageResultAction extends TmsAction {

	private static final String IMGTYPE = "imgType";// 1：车辆整体图片
	private static final String IMGKEY = "imgKey";// 图片位置key
	private static final String SEEPIC = "seePic";
	private static final String UPPIC = "upPic";
	private static final String IMAGEERROR = "imageError";

	@SuppressWarnings("unchecked")
	@Override
	protected ActionForward doAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response, UserContext uc) throws Exception {

		String forward = "";

		// 从form中
		TransferRgActionForm transferRgActionForm = (TransferRgActionForm) form;
		TransferRgInputViewHelper viewhelp = new TransferRgInputViewHelper();
		if (transferRgActionForm.getBackButton() != null) {
			viewhelp.setSeePicFlag(false);
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
			request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
			transferRgActionForm.setBackButton(null);
			viewhelp.setImageFlag("0");
			forward = UPPIC;
		} else {
			// 显示图片的button
			if (transferRgActionForm.getSeePicButton() != null) {
				// String imgPath = carImgForm.getImgPath();
				FormFile formfil = transferRgActionForm.getImgPath();
				/** 判断图片后缀名是否正常 **/
				// 判断图片是否正确
				if (imageAll(formfil)) {
					setErrorsToRequest(request, TmsConstants.I0015, null);
					viewhelp.setImageFlag("0");
					uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
					request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
					return mapping.findForward(IMAGEERROR);
				} else if (formfil.getFileSize() > 1048576) {
					setErrorsToRequest(request, TmsConstants.I0018, null);
					viewhelp.setImageFlag("0");
					uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
					request.setAttribute(TmsConstants.VIEWHELP, uc.getAttribute(TmsConstants.VIEWHELP));
					return mapping.findForward(IMAGEERROR);
				}
				viewhelp.setImageFlag("1");
				String path = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY));
				String img = System.currentTimeMillis() + ".jpg";// 图片名称
				FileOutputStream fileOutput = new FileOutputStream(new File(path + img));
				fileOutput.write(formfil.getFileData());
				fileOutput.flush();
				viewhelp.setSeePic(ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOADTMP_CONTEXT_ROOT_KEY) + img));
				// 前台显示出隐藏部分的图片
				viewhelp.setSeePicFlag(true);
				uc.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				// 返回当前页面 要对form的值重新set
				transferRgActionForm.setSeePicButton(null);
				request.setAttribute(TmsConstants.VIEWHELP, viewhelp);
				forward = SEEPIC;
			} else {

				// 把一组数据打包存如entity中
				CarImage entity = CarImage.getInstance();
				viewhelp = (TransferRgInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
				entity.setImgPath(viewhelp.getSeePic());// 这个Path需要处理一下
				String sysPath = request.getSession().getServletContext().getRealPath("/").replace("/tmsweb", "");

				File inFile = null;
				File outFile2 = null;
				String serial = (String) uc.getAttribute("imgSerial");
				if (serial != "" && serial != null) {
					TransferAcceptedInfo accept = new TransferAcceptedInfo();
					accept = accept.getAssessInfoBySerial(serial);
					//
					inFile = new File(sysPath + viewhelp.getSeePic());
					String outFile = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY) + "/" + serial + "/");
					outFile2 = new File(outFile + "/" + serial + "_1" + ".jpg");
					CopyFile.copy(inFile, outFile2);
					
					//
					String url = ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.WWW_CHECKPAD_IMAGE_UPLOAD_PUT_KEY)+ "/" + serial + "/" + serial + "_1" + ".jpg");
					TmsUserProfile profile = uc.getUserProfile();
					TransferAcceptedInfo accept1 = new TransferAcceptedInfo();
					accept1.setSerial(serial);
					accept1.setPicChangeNum(accept.getPicChangeNum() + 1);
					accept1.setPicChangeUserId(profile.getUniqueId());
					accept1.setUpdateUserId(profile.getUniqueId());
					accept1.setPhoto_1(url);
					accept1.updatePicNum(accept1);
					//
					TransferProcessHistory his = new TransferProcessHistory();
					his.setBusinessType(44);
					his.setInsertUserId(profile.getUniqueId());
					his.setSerial(serial);
					his.insertHisInfoAtAssess(his);
				}

				// 前台不显示隐藏部分的图片
				viewhelp.setSeePicFlag(false);
				// 放到一个list中，每次存的时候往里面ADD一下就可以了
				viewhelp.setImageFlag("0");
				uc.setAttribute("serial", serial);
				forward = UPPIC;

			}
		}

		return mapping.findForward(forward);
	}

	/***
	 * 图片名称验证
	 */
	public boolean imageAll(FormFile file) {
		int i = 0;
		String type = file.getFileName();
		if (type.length() == 0)
			return true;
		while (i != -1) {
			// 找到上传文件的类型的位置，这个地方的是'.'
			i = type.indexOf(".");
			/* 截取上传文件的后缀名,此时得到了文件的类型 */
			type = type.substring(i + 1).toLowerCase();
		}
		if (!type.equals("jpg") && !type.equals("jpeg") && !type.equals("gif")) {
			return true;
		} else {
			return false;
		}
	}
}
